package com.wsj.web.action.BmSite;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.wsj.service.IBmClassTypeServ;
import com.wsj.service.IHomeSiteAdBannerDescriptServ;
import com.wsj.service.IHomeSiteNewsClassServ;
import com.wsj.util.exception.BusinessException;
import com.wsj.util.page.PageResultSet;
import com.wsj.util.tool.StringUtils;
import com.wsj.web.action.BaseAction;
import com.wsj.web.constant.page.PageContent;
import com.wsj.web.form.BmSite.HomeSiteAdBannerDesExtBean;
import com.wsj.web.form.BmSite.HomeSiteAdBannerDescriptionForm;
import com.wsj.web.vo.homeSite.BmClassType;
import com.wsj.web.vo.homeSite.HomeSiteAdBannerDescription;
import com.wsj.web.vo.homeSite.HomeSiteNewsClass;

public class HomeSiteAdBannerDespriteAction extends BaseAction{

	private IHomeSiteAdBannerDescriptServ homeSiteAdBannerDescriptServ;
	
	private IHomeSiteNewsClassServ homeSiteNewsClassServ;
	
	private IBmClassTypeServ bmClassTypeServImpl;
	
	
	/* 添加广告描述  第一步： */
	public ActionForward toAdd(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){
		String topage = "bannerDes_add";
		try {
			Integer typeId = this.getTypeId();  // 广告分类
			// 获取第一级分类下面的所有属于广告中的分类
			List firstClassList  = this.getHomeSiteNewsClassServ().loadFirstHomeSiteNewsClassByType(typeId);
			if(firstClassList == null || firstClassList.isEmpty())
			{
				firstClassList = new ArrayList();
			}
			request.setAttribute("firstHomeSiteNewsClassList",firstClassList);
			
		} catch (BusinessException e) {
			e.printStackTrace();
		}
		
		return mapping.findForward(topage);
	}
	
	/* 添加广告描述  第二步： */
	public ActionForward add(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		String topage = "/admin/banner/homeSiteAdBannerDesprite.do?action=toAdd";
		
		HomeSiteAdBannerDescriptionForm hsForm = (HomeSiteAdBannerDescriptionForm)form;
		HomeSiteAdBannerDescription hs = new HomeSiteAdBannerDescription();
		try {
			BeanUtils.copyProperties(hs, hsForm);
			
			Long classId = this.loadClassId(hsForm);
			HomeSiteNewsClass hsc = this.homeSiteNewsClassServ.loadNewsClassById(classId);
			if(hsc!=null){
				hs.setHomeSiteNewsClass(hsc);
				this.homeSiteAdBannerDescriptServ.add(hs);
				request.setAttribute("msg","<script>alert('添加成功！');</script>");
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (BusinessException e) {
			e.printStackTrace();
		}
		
		return new ActionForward(topage);
	}
	
	

	/* 修改广告描述  第一步： */
	@SuppressWarnings("unchecked")
	public ActionForward toUpdate(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		String topage = "bannerDes_update";
		
		HomeSiteAdBannerDescription hs = new HomeSiteAdBannerDescription();
		HomeSiteAdBannerDesExtBean hsExt = new HomeSiteAdBannerDesExtBean();
		try {
			String idStr = request.getParameter("id");
			Integer id = Integer.parseInt(idStr);
			hs = this.homeSiteAdBannerDescriptServ.loadHsAdBannerById(id);
			BeanUtils.copyProperties(hsExt, hs);
			Integer typeId = this.getTypeId();
			
			// 获取第一级分类下面的所有属于广告中的分类
			List<HomeSiteNewsClass>  firstClassList = this.getHomeSiteNewsClassServ().loadFirstHomeSiteNewsClassByType(typeId);
			if(StringUtils.isNotNull(firstClassList))
			{
				request.setAttribute("firstHomeSiteNewsClassList",firstClassList);
			}
			
			
			//获得老的二级分类和三级分类
			//this.loadOldNewsClass(request,hsExt);
			
			Long classId = hs.getHomeSiteNewsClass().getId();
			HomeSiteNewsClass hsnews = this.homeSiteNewsClassServ.loadNewsClassById(classId);
			hsExt.setNewsClassName(hsnews.getNames());
			hsExt.setHsNewsClassId(hsnews.getId());
			request.setAttribute("hsDes", hsExt);
						
			request.setAttribute("bk_page", request.getParameter("bk_page"));
			String bk_description = request.getParameter("bk_description");
			if(StringUtils.isNotNull(bk_description)){
				bk_description = new String(bk_description.trim().getBytes("ISO-8859-1"),"UTF-8");
			}
			request.setAttribute("bk_description", bk_description);
			request.setAttribute("bk_newsClassId", request.getParameter("bk_newsClassId"));
			request.setAttribute("bk_firstNewsClassId", request.getParameter("bk_firstNewsClassId"));
			request.setAttribute("bk_secondNewsClassId", request.getParameter("bk_secondNewsClassId"));
			request.setAttribute("bk_thirdNewsClassId", request.getParameter("bk_thirdNewsClassId"));
			
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (BusinessException e) {
			e.printStackTrace();
		}
		
		return mapping.findForward(topage);
	}
	
	
	/* 修改广告描述  第二步： */
	public ActionForward update(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		String topage = "bannerDesList";
		HomeSiteAdBannerDescriptionForm hsForm = (HomeSiteAdBannerDescriptionForm)form;
		HomeSiteAdBannerDescription hs = new HomeSiteAdBannerDescription();
		try {
			hs = this.homeSiteAdBannerDescriptServ.loadHsAdBannerById(hsForm.getId());
			BeanUtils.copyProperties(hs, hsForm);
			/* 关联关系 */
			//分类id
			Long classId = this.loadClassId(hsForm);
			if(classId == null){
				classId = hsForm.getHsNewsClassId();
			}
			HomeSiteNewsClass hsnews = this.homeSiteNewsClassServ.loadNewsClassById(classId);
			hs.setHomeSiteNewsClass(hsnews);
			this.homeSiteAdBannerDescriptServ.update(hs);
			request.setAttribute("msg","<script>alert('修改成功！');</script>");
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (BusinessException e) {
			e.printStackTrace();
		}
		this.backToPage(request);  //  返回到原来的页面
		return mapping.findForward(topage);
	}
	
	/* 删除（伪删除）广告描述  0否1是：是改成否，否改成是 */
	public ActionForward delete(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		String topage = "bannerDesList";
		
		HomeSiteAdBannerDescriptionForm hsForm = (HomeSiteAdBannerDescriptionForm)form;
		HomeSiteAdBannerDescription hs = new HomeSiteAdBannerDescription();
		try {
			String[] obj =  hsForm.getCheckboxparam();
			for(int i=0;i<obj.length;i++){
				Integer id = Integer.parseInt(obj[i]);
				hs = this.homeSiteAdBannerDescriptServ.loadHsAdBannerById(id);
				if(hs!=null){
					Short isDel = hs.getDel();
					if(isDel.equals((short)1)){
						hs.setDel((short) 0);
					}else{
						hs.setDel((short) 1);
					}
					
					this.homeSiteAdBannerDescriptServ.update(hs);
				}
			}
			this.setPopMsg(request, "msg", "删除成功！");
		} catch (BusinessException e) {
			e.printStackTrace();
		}
		this.backToPage(request);  //  返回到原来的页面
		return mapping.findForward(topage);
		
	}
	
	/* 获取广告描述列表 */
	public ActionForward list(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		String topage = "bannerDesList";
		this.backToPage(request);  //  返回到原来的页面
		return mapping.findForward(topage);
	}
	
	/* 按 描述、分类 搜索 */
	public ActionForward search(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		String topage = "bannerDesList";
		Integer page = 1;
		Integer pageSize = 15;
		HomeSiteAdBannerDescriptionForm hsForm = (HomeSiteAdBannerDescriptionForm)form;
		String picInfo = hsForm.getPicInfo();
		Long firstNewsClassId = hsForm.getFirstNewsClassId();
		Long secondNewsClassId = hsForm.getSecondNewsClassId();
		Long thirdNewsClassId = hsForm.getThirdNewsClassId();
		Long classId = this.loadClassId(hsForm);
		if(firstNewsClassId != null && !new Long(-1).equals(firstNewsClassId)){
			Map<Long,String>secondNewsClassList = this.secondNewsClassListByFirstClassId(firstNewsClassId);
			  if(secondNewsClassList != null && secondNewsClassList.size() > 0){
				  request.setAttribute("secondNewsClassList", secondNewsClassList);
			  }
		}
		
		if(secondNewsClassId != null && !new Long(-1).equals(secondNewsClassId)){
			Map<Long,String>thirdNewsClassList = this.secondNewsClassListByFirstClassId(secondNewsClassId);
			  if(thirdNewsClassList != null && thirdNewsClassList.size() > 0){
				  request.setAttribute("thirdNewsClassList", thirdNewsClassList);
			  }
		}
		this.loadPageList(firstNewsClassId,secondNewsClassId,thirdNewsClassId,classId, picInfo, request,page,pageSize);
		return mapping.findForward(topage);
	}
	
	
	/*****
	 * 获得选择的id
	 * @param hsForm
	 * @return
	 */
	private Long loadClassId(HomeSiteAdBannerDescriptionForm hsForm) 
	{
		Long id = null;
		if(hsForm.getThirdNewsClassId()!=null && hsForm.getThirdNewsClassId().intValue()!=-1)
		{
			id = hsForm.getThirdNewsClassId();
		}
		else if(hsForm.getSecondNewsClassId()!=null && hsForm.getSecondNewsClassId().intValue()!=-1)
		{
			id=hsForm.getSecondNewsClassId();
		}
		else if (hsForm.getFirstNewsClassId()!=null  && hsForm.getFirstNewsClassId().intValue()!=-1)
		{
			id=hsForm.getFirstNewsClassId();
		}
		
		return id;
	}
	
	
	
	/*****
	 * 通过一级分类id加载二级分类下面的分类列表
	 * @param parenId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Map<Long, String> thirdNewsClassListByFirstClassId(Long parenId) 
	{
	  try 
		{
			return  this.getHomeSiteNewsClassServ().loadSecondHomeSiteNewsClassByAdType(parenId);
		} catch (BusinessException e) {
			e.printStackTrace();
		}
		return new HashMap();
	}


	/*****
	 * 通过二级分类id,加载二级分类下面的分类列表
	 * @param parenId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Map<Long, String> secondNewsClassListByFirstClassId(Long parenId) 
	{
		  try {
				return  this.getHomeSiteNewsClassServ().loadSecondHomeSiteNewsClassByAdType(parenId);
			} catch (BusinessException e) {
				e.printStackTrace();
			}
			
			return new HashMap();
	}
		
	
	
	private void backToPage(HttpServletRequest request) throws UnsupportedEncodingException{
		Integer page = 1;
		Integer pageSize = 15;
		Long newsClassId = null;
		Long firstNewsClassId = null;
		Long secondNewsClassId = null;
		Long thirdNewsClassId = null;
		
		
		String pageStr = request.getParameter("bk_page");
		String description = request.getParameter("bk_description");
		String newsClassIdStr = request.getParameter("bk_newsClassId");
		String firstNewsClassIdStr = request.getParameter("bk_firstNewsClassId");
		String secondNewsClassIdStr = request.getParameter("bk_secondNewsClassId");
		String thirdNewsClassIdStr = request.getParameter("bk_thirdNewsClassId");
		
		if(StringUtils.isNotNull(pageStr)){
			page = Integer.parseInt(pageStr);
		}
		if(StringUtils.isNotNull(newsClassIdStr)){
			newsClassId = Long.parseLong(newsClassIdStr);
		}
		if(StringUtils.isNotNull(description)){
			description = new String(description.trim().getBytes("ISO-8859-1"),"UTF-8");
		}		
		if(StringUtils.isNotNull(firstNewsClassIdStr)){
			firstNewsClassId = Long.parseLong(firstNewsClassIdStr);
		}
		if(StringUtils.isNotNull(secondNewsClassIdStr)){
			secondNewsClassId = Long.parseLong(secondNewsClassIdStr);
		}
		if(StringUtils.isNotNull(thirdNewsClassIdStr)){
			thirdNewsClassId = Long.parseLong(thirdNewsClassIdStr);
		}
		
		if(firstNewsClassId != null){
			Map<Long,String>secondNewsClassList = this.secondNewsClassListByFirstClassId(firstNewsClassId);
			  if(secondNewsClassList != null && secondNewsClassList.size() > 0){
				  request.setAttribute("secondNewsClassList", secondNewsClassList);
			  }
		}
		
		if(secondNewsClassId != null){
			Map<Long,String>thirdNewsClassList = this.secondNewsClassListByFirstClassId(secondNewsClassId);
			  if(thirdNewsClassList != null && thirdNewsClassList.size() > 0){
				  request.setAttribute("thirdNewsClassList", thirdNewsClassList);
			  }
		}
		
		this.loadPageList(firstNewsClassId,secondNewsClassId,thirdNewsClassId,newsClassId, description, request, page, pageSize);
	}
	
	
	@SuppressWarnings("unchecked")
	private  void loadPageList(Long firstNewsClassId,Long secondNewsClassId,Long thirdNewsClassId,Long newsClassId,String description,HttpServletRequest request,Integer page, Integer pageSize)
	{
		 try {

			  PageResultSet pageResultSet = this.homeSiteAdBannerDescriptServ.loadPageList(newsClassId, description, page, pageSize);
			  
			  if(pageResultSet!=null)
			  {
			      //设置上一页
			      request.setAttribute(PageContent.backPage,pageResultSet.getBackPage());
			      //下一页
			      request.setAttribute(PageContent.nextPage,pageResultSet.getNextPage());
			      //当前页
			      request.setAttribute(PageContent.curPage,pageResultSet.getCurPage());
			      //总共页数
			      request.setAttribute(PageContent.allPage,pageResultSet.getAllPage());
			      request.setAttribute(PageContent.pageSize, pageResultSet.getPageSize());
			      //总记录数
			      request.setAttribute(PageContent.recordNum,pageResultSet.getRecordNum());
			      //开始行码
			      request.setAttribute(PageContent.startRow,pageResultSet.getStartRow());
			      //结束行码
			      request.setAttribute(PageContent.endRow,pageResultSet.getEndRow());
			      
			      List<HomeSiteAdBannerDescription> li = pageResultSet.getResult();
			        
			      List<HomeSiteAdBannerDesExtBean> liExt = new ArrayList<HomeSiteAdBannerDesExtBean>();
			      for(int i=0;i<li.size();i++){
			    	  HomeSiteAdBannerDescription hs = new HomeSiteAdBannerDescription();
			    	  HomeSiteAdBannerDesExtBean hsExt = new HomeSiteAdBannerDesExtBean();	
			    	  hs = (HomeSiteAdBannerDescription)li.get(i);
			    	  Long claId = hs.getHomeSiteNewsClass().getId();
					  HomeSiteNewsClass hsn = this.homeSiteNewsClassServ.loadNewsClassById(claId);
					  if(hsn != null){
							hsExt.setNewsClassName(hsn.getNames());
					  }
					  BeanUtils.copyProperties(hsExt, hs);
			    	  liExt.add(hsExt);
			      }
			      
			      request.setAttribute("descriptList",liExt);
			  }      
			     
			  if(StringUtils.isNotNull(description)){
					request.setAttribute("bk_description", description);
			  }
			  
			  if(newsClassId != null && !new Long(-1).equals(newsClassId)){
				  request.setAttribute("bk_newsClassId", newsClassId);
			  }
			  if(firstNewsClassId != null && !new Long(-1).equals(firstNewsClassId)){
				  request.setAttribute("bk_firstNewsClassId", firstNewsClassId);
			  }
			  if(secondNewsClassId != null && !new Long(-1).equals(secondNewsClassId)){
				  request.setAttribute("bk_secondNewsClassId", secondNewsClassId);
			  }
			  if(thirdNewsClassId != null && !new Long(-1).equals(thirdNewsClassId)){
				  request.setAttribute("bk_thirdNewsClassId", thirdNewsClassId);
			  }
			  
			  Integer typeId = this.getTypeId();
			  if(typeId != null){
				  List<HomeSiteNewsClass>firstHomeSiteNewsClassList = this.homeSiteNewsClassServ.loadFirstHomeSiteNewsClassByType(typeId);
				  if(StringUtils.isNotNull(firstHomeSiteNewsClassList)){
					  request.setAttribute("firstHomeSiteNewsClassList", firstHomeSiteNewsClassList);
				  }
			  }
//			  String classStr = this.homeSiteNewsClassServ.getChildStr(new Long(-1),typeId, 0, -1);
//			  request.setAttribute("classStr",classStr);
			  
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (BusinessException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
          
	}
	
	
	private Integer getTypeId() throws BusinessException{
		//	  广告分类
		Integer typeId = 0;
		BmClassType bmt = this.bmClassTypeServImpl.getBmClassTypeByClassTypeName("广告类别");
		if(bmt!=null){
			typeId = bmt.getId();
		}
		return typeId;
	}
	
	public IHomeSiteAdBannerDescriptServ getHomeSiteAdBannerDescriptServ() {
		return homeSiteAdBannerDescriptServ;
	}


	public void setHomeSiteAdBannerDescriptServ(
			IHomeSiteAdBannerDescriptServ homeSiteAdBannerDescriptServ) {
		this.homeSiteAdBannerDescriptServ = homeSiteAdBannerDescriptServ;
	}


	public IHomeSiteNewsClassServ getHomeSiteNewsClassServ() {
		return homeSiteNewsClassServ;
	}


	public void setHomeSiteNewsClassServ(
			IHomeSiteNewsClassServ homeSiteNewsClassServ) {
		this.homeSiteNewsClassServ = homeSiteNewsClassServ;
	}

	public IBmClassTypeServ getBmClassTypeServImpl() {
		return bmClassTypeServImpl;
	}

	public void setBmClassTypeServImpl(IBmClassTypeServ bmClassTypeServImpl) {
		this.bmClassTypeServImpl = bmClassTypeServImpl;
	}

}
